package theOrbalEra.common.network;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import theOrbalEra.client.ClientProxy;
import theOrbalEra.common.player.PlayerHandler;
import theOrbalEra.common.player.PlayerStatistics;
import theOrbalEra.common.util.DefultValue;
import theOrbalEra.common.util.idList.PacketId;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.NetLoginHandler;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet1Login;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.server.MinecraftServer;

import com.google.common.io.ByteArrayDataInput;

import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.IConnectionHandler;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.relauncher.Side;

public class PacketPlayerDataSave extends PacketBase implements IConnectionHandler {
	public static boolean isRemote = false;
	/** 0 = none, 1 = integrated, 2 = dedicated*/
	public static int typeOfServer;
	@Override
	public void readClient(int id, ByteArrayDataInput dat, Object[] extradata) {
		int level = dat.readInt();
		int experience=dat.readInt();
		int HP = dat.readInt();
		int EP = dat.readInt();
		int MAX_HP = dat.readInt();
		int MAX_EP = dat.readInt();
		String username = dat.readLine();
		
		PlayerHandler.addPlayer(username, new PlayerHandler((EntityPlayer) extradata[0], new PlayerStatistics()));
		
		if(ClientProxy.getPlayer().username.equals(username)) {
			PlayerHandler.getPlayer(username).getStats().level = level;
			PlayerHandler.getPlayer(username).getStats().experience = experience;
			PlayerHandler.getPlayer(username).getStats().HP = HP;
			PlayerHandler.getPlayer(username).getStats().EP = EP;
			PlayerHandler.getPlayer(username).getStats().MAX_HP = MAX_HP;
			PlayerHandler.getPlayer(username).getStats().MAX_EP = MAX_EP;
			}
	}
	@Override
	public void readServer(int id, ByteArrayDataInput dat, Object[] extradata) {
		int level = dat.readInt();
		int experience=dat.readInt();
		int HP = dat.readInt();
		int EP = dat.readInt();
		int MAX_HP = dat.readInt();
		int MAX_EP = dat.readInt();
		String username = dat.readLine();
		writeData(level,experience,  HP, EP, MAX_HP, MAX_EP,username);
		
		PlayerStatistics stats = PlayerHandler.getPlayer(username).getStats();
		stats.level = level;
		stats.experience=experience;
		stats.HP = HP;
		stats.EP = EP;
		stats.MAX_HP = MAX_HP;
		stats.MAX_EP = MAX_EP;	
		}
	
	
	public void writeData(int level,int experience,int HP, int EP, int MAX_HP, int MAX_EP, String username) {
		EntityPlayerMP player = FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().getPlayerForUsername(username);
		NBTTagCompound oldNBT = player.getEntityData();
		NBTTagCompound nbt = oldNBT.getCompoundTag("AdvStories");
		if(!oldNBT.hasKey("AdvStories")) {
			oldNBT.setCompoundTag("AdvStories", nbt);
		}
		NBTTagCompound playerNBT=nbt.getCompoundTag(username);
		if(!nbt.hasKey(username)) {
			nbt.setCompoundTag(username, playerNBT);
		}
		playerNBT.setInteger("level", level);
		playerNBT.setInteger("experience", experience);
		playerNBT.setInteger("HP", HP);
		playerNBT.setInteger("EP", EP);
		playerNBT.setInteger("MAX_HP",MAX_HP);
		playerNBT.setInteger("MAX_EP",MAX_EP);
		
	}

	
	public void readData(String username) {
		EntityPlayerMP player = FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().getPlayerForUsername(username);
		NBTTagCompound oldNBT = player.getEntityData();
		NBTTagCompound nbt = oldNBT.getCompoundTag("AdvStories");
		if(oldNBT.hasKey("AdvStories")){
			NBTTagCompound playerNBT=nbt.getCompoundTag(username);
			if(nbt.hasKey(username)) {
				PlayerHandler.getPlayer(username).getStats().level = playerNBT.getInteger("level");
				PlayerHandler.getPlayer(username).getStats().experience = playerNBT.getInteger("experience");
				PlayerHandler.getPlayer(username).getStats().HP = playerNBT.getInteger("HP");
				PlayerHandler.getPlayer(username).getStats().EP = playerNBT.getInteger("EP");
				PlayerHandler.getPlayer(username).getStats().MAX_HP = playerNBT.getInteger("MAX_HP");
				PlayerHandler.getPlayer(username).getStats().MAX_EP = playerNBT.getInteger("MAX_EP");
				
			}
			
		} 
		else 
			PlayerHandler.getPlayer(username).setDefaults();
		sendSaveData(username, PlayerHandler.getPlayer(username).getStats());
	}

	/**
	 * Sends data for a specific player back to the client or server.
	 * @param username username
	 * @param stats instance
	 */
	public static void sendSaveData(String username, PlayerStatistics stats) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream(110);
		DataOutputStream dos = new DataOutputStream(bos);

		try {
			dos.writeInt(PacketId.PLAYER_DATA);
			dos.writeInt(stats.level);
			dos.writeInt(stats.experience);
			dos.writeInt(stats.HP);
			dos.writeInt(stats.EP);
			dos.writeInt(stats.MAX_HP);
			dos.writeInt(stats.MAX_EP);
			dos.writeBytes(username);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Packet250CustomPayload pkt = new Packet250CustomPayload();
		pkt.channel = DefultValue.channel;
		pkt.data = bos.toByteArray();
		pkt.length = bos.size();
		pkt.isChunkDataPacket = false;
		if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) 
			PacketDispatcher.sendPacketToServer(pkt);
		if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) {
			EntityPlayerMP player = FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().getPlayerForUsername(username);
			
			PacketDispatcher.sendPacketToPlayer(pkt, (Player) player);
		}
	}
	
	@Override
	public void playerLoggedIn(Player other, NetHandler netHandler, INetworkManager manager) {
		EntityPlayer player = (EntityPlayer)other;
		PlayerHandler.addPlayer(player.username, new PlayerHandler(player, new PlayerStatistics()));
		if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) {
			readData(player.username);
		}
		
	}
	
	@Override
	public void connectionClosed(INetworkManager manager) {
	}

	@Override
	public String connectionReceived(NetLoginHandler netHandler, INetworkManager manager) {
		return null;
	}

	@Override
	public void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager manager) {
		isRemote = true;
		typeOfServer = 2;
	}

	@Override
	public void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager manager) {
		typeOfServer = 1;
		isRemote = true; 
	}

	@Override
	public void clientLoggedIn(NetHandler clientHandler, INetworkManager manager, Packet1Login login) {
	}
}
